package com.robotserver.orders.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.doudian.open.api.buyin_doukeOrderAds.BuyinDoukeOrderAdsRequest;
import com.doudian.open.api.buyin_doukeOrderAds.BuyinDoukeOrderAdsResponse;
import com.doudian.open.api.buyin_doukeOrderAds.data.OrdersItem;
import com.doudian.open.api.buyin_doukeOrderAds.data.PidInfo;
import com.doudian.open.api.buyin_doukeOrderAds.param.BuyinDoukeOrderAdsParam;
import com.doudian.open.core.AccessToken;
import com.doudian.open.core.AccessTokenBuilder;
import com.robotserver.orders.common.DateUtil;
import com.robotserver.orders.common.Math;
import com.robotserver.orders.entity.DyOrders;
import com.robotserver.orders.entity.DyTokens;
import com.robotserver.orders.mapper.SysSettingMapper;
import com.robotserver.orders.mapper.DyOrdersMapper;
import com.robotserver.orders.mapper.DyTokensMapper;
import com.robotserver.orders.service.DyOrderSyncService;
import com.robotserver.orders.vo.DyOrderTimeVO;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther: jianghan
 * @Date: 2020/12/2 14:05
 * @Description:
 */
@Service
public class DyOrderSyncServiceImpl implements DyOrderSyncService {

    private static Logger logger = LoggerFactory.getLogger(DyOrderSyncServiceImpl.class);

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private DyTokensMapper dyTokensMapper;
    @Autowired
    private SysSettingMapper sysSettingMapper;
    @Autowired
    private DyOrdersMapper dyOrdersMapper;

    @Override
    public void syncOpenUnitOrder(List<DyOrderTimeVO> dyOrderTimeVOS, DyTokens token, Integer downType) {
        for (DyOrderTimeVO time:dyOrderTimeVOS){
            syncTimeUnitOrder(time, token,"0", downType); //cursor下一页索引（第一页传“0”）
        }
    }

    @Override
    public void syncTimeUnitOrder(DyOrderTimeVO time, DyTokens token, String cursor, Integer downType) {
        try {
            String dy_app_key = sysSettingMapper.getByKey("dy_app_key");
            String dy_app_secret = sysSettingMapper.getByKey("dy_app_secret");

            BuyinDoukeOrderAdsRequest request = new BuyinDoukeOrderAdsRequest();
            BuyinDoukeOrderAdsParam param = request.getParam();
            param.setSize(40L);
            param.setCursor(cursor);
            param.setStartTime(time.getBeginTime());
            param.setEndTime(time.getEndTime());
            if(downType == null){
                param.setTimeType("update");
            }else{
                if(downType == 1){
                    param.setTimeType("pay");
                }else{
                    param.setTimeType("update");
                }
            }

            AccessToken accessToken = AccessTokenBuilder.parse(token.getAccessToken());
            BuyinDoukeOrderAdsResponse response = request.execute(accessToken);
            if (response != null && response.getData() != null && response.getData().getOrders() != null && response.getData().getOrders().size() > 0){
                // 处理订单入库
                ordersAdd(response.getData().getOrders(), token);
                //下页的索引
                String cursor_next = response.getData().getCursor();
                syncTimeUnitOrder(time, token, cursor_next, downType);
            }
        } catch (Exception e) {
            logger.error("dy sync order err:{}", e.getMessage());
        }
    }

    @Override
    public void ordersAdd(List<OrdersItem> orderInfoList, DyTokens dyTokens) {
        for (OrdersItem orderInfo: orderInfoList){
            try {

                int bizstatus = bizStatus(orderInfo.getFlowPoint());
                if (bizstatus == -1){
                     // continue;
                }

                int now = DateUtil.getNowTime();

                // 根据订单号查询商品是否存在
                DyOrders dyOrders = dyOrdersMapper.getByOrderId(orderInfo.getOrderId());
                if (dyOrders == null){

                    logger.info("---DY orders add;  orderId:{}, productId:{}, status:{}, modifytime:{}",new Object[]{orderInfo.getOrderId(), orderInfo.getProductId(), orderInfo.getFlowPoint(), orderInfo.getUpdateTime()});

                    dyOrders = new DyOrders();
                    dyOrders.setId(IdWorker.getId());
                    dyOrders.setOrderId(orderInfo.getOrderId());
                    dyOrders.setConfirmTime(DateUtil.getStrTime(orderInfo.getConfirmTime()));
                    dyOrders.setMaterialId(orderInfo.getMaterialId());
                    dyOrders.setAuthorBuyinId(orderInfo.getAuthorBuyinId());
                    dyOrders.setProductId(orderInfo.getProductId());
                    dyOrders.setProductName(orderInfo.getProductName());
                    dyOrders.setProductImg(orderInfo.getProductImg());
                    dyOrders.setAuthorAccount(orderInfo.getAuthorAccount());
                    dyOrders.setShopName(orderInfo.getShopName());
                    dyOrders.setTotalPayAmount(Math.div(orderInfo.getTotalPayAmount() == null ? 0 : orderInfo.getTotalPayAmount(), 100));
                    dyOrders.setFlowPoint(orderInfo.getFlowPoint());
                    dyOrders.setModifyTime(DateUtil.getStrTime(orderInfo.getUpdateTime()));
                    dyOrders.setPaySuccessTime(DateUtil.getStrTime(orderInfo.getPaySuccessTime()));
                    dyOrders.setSettleTime(DateUtil.getStrTime(orderInfo.getSettleTime()));
                    dyOrders.setPayGoodsAmount(Math.div(orderInfo.getPayGoodsAmount() == null ? 0 : orderInfo.getPayGoodsAmount(), 100));
                    dyOrders.setSettledGoodsAmount(Math.div(orderInfo.getSettledGoodsAmount() == null ? 0 : orderInfo.getSettledGoodsAmount(), 100));
                    dyOrders.setShopId(orderInfo.getShopId());

                    //分销订单相关参数
                    PidInfo pidInfo = orderInfo.getPidInfo();
                    if(pidInfo != null){
                        dyOrders.setPid(pidInfo.getPid());
                        dyOrders.setExternalInfo(pidInfo.getExternalInfo());
                        dyOrders.setMediaTypeName(pidInfo.getMediaTypeName());
                    }
                    dyOrders.setItemNum(orderInfo.getItemNum());
                    dyOrders.setRefundTime(DateUtil.getStrTime(orderInfo.getRefundTime()));
                    dyOrders.setAdsEstimatedCommission(Math.div(orderInfo.getAdsEstimatedCommission() == null ? 0 : orderInfo.getAdsEstimatedCommission(), 100));
                    dyOrders.setAdsRealCommission(Math.div(orderInfo.getAdsRealCommission() == null ? 0 : orderInfo.getAdsRealCommission(), 100));
                    dyOrders.setAuthorShortId(orderInfo.getAuthorShortId());
                    dyOrders.setAdsPromotionRate(Math.div(orderInfo.getAdsPromotionRate() == null ? 0 : orderInfo.getAdsPromotionRate(), 100));
                    dyOrders.setMediaType(orderInfo.getMediaType());
                    dyOrders.setAdsActivityId(orderInfo.getAdsActivityId());
                    dyOrders.setAdsEstimatedTechServiceFee(Math.div(orderInfo.getAdsEstimatedTechServiceFee() == null ? 0 : orderInfo.getAdsEstimatedTechServiceFee(), 100));
                    dyOrders.setAdsFansType(orderInfo.getAdsFansType());
                    dyOrders.setProductActivityId(orderInfo.getProductActivityId());
                    dyOrders.setBizStatus(bizstatus);
                    dyOrders.setCreateTime(now);
                    dyOrders.setUpdateTime(now);
                    dyOrders.setTokenType(0); //抖音抖客订单
                    dyOrders.setTokenId(dyTokens.getAppId());

                    //抖音订单增加
                    dyOrdersMapper.add(dyOrders);

                }else {
                    logger.info("---DY orders update;  orderId:{}, productId:{}, status:{}, modifytime:{}",new Object[]{orderInfo.getOrderId(), orderInfo.getProductId(), orderInfo.getFlowPoint(), orderInfo.getUpdateTime()});

                    dyOrders.setOrderId(orderInfo.getOrderId());
                    dyOrders.setConfirmTime(DateUtil.getStrTime(orderInfo.getConfirmTime()));
                    dyOrders.setMaterialId(orderInfo.getMaterialId());
                    dyOrders.setAuthorBuyinId(orderInfo.getAuthorBuyinId());
                    dyOrders.setProductId(orderInfo.getProductId());
                    dyOrders.setProductName(orderInfo.getProductName());
                    dyOrders.setProductImg(orderInfo.getProductImg());
                    dyOrders.setAuthorAccount(orderInfo.getAuthorAccount());
                    dyOrders.setShopName(orderInfo.getShopName());
                    dyOrders.setTotalPayAmount(Math.div(orderInfo.getTotalPayAmount() == null ? 0 : orderInfo.getTotalPayAmount(), 100));
                    dyOrders.setFlowPoint(orderInfo.getFlowPoint());
                    dyOrders.setModifyTime(DateUtil.getStrTime(orderInfo.getUpdateTime()));
                    dyOrders.setPaySuccessTime(DateUtil.getStrTime(orderInfo.getPaySuccessTime()));
                    dyOrders.setSettleTime(DateUtil.getStrTime(orderInfo.getSettleTime()));
                    dyOrders.setPayGoodsAmount(Math.div(orderInfo.getPayGoodsAmount() == null ? 0 : orderInfo.getPayGoodsAmount(), 100));
                    dyOrders.setSettledGoodsAmount(Math.div(orderInfo.getSettledGoodsAmount() == null ? 0 : orderInfo.getSettledGoodsAmount(), 100));
                    dyOrders.setShopId(orderInfo.getShopId());

                    //分销订单相关参数
                    PidInfo pidInfo = orderInfo.getPidInfo();
                    if(pidInfo != null){
                        dyOrders.setPid(pidInfo.getPid());
                        dyOrders.setExternalInfo(pidInfo.getExternalInfo());
                        dyOrders.setMediaTypeName(pidInfo.getMediaTypeName());
                    }
                    dyOrders.setItemNum(orderInfo.getItemNum());
                    dyOrders.setRefundTime(DateUtil.getStrTime(orderInfo.getRefundTime()));
                    dyOrders.setAdsEstimatedCommission(Math.div(orderInfo.getAdsEstimatedCommission() == null ? 0 : orderInfo.getAdsEstimatedCommission(), 100));
                    dyOrders.setAdsRealCommission(Math.div(orderInfo.getAdsRealCommission() == null ? 0 : orderInfo.getAdsRealCommission(), 100));
                    dyOrders.setAuthorShortId(orderInfo.getAuthorShortId());
                    dyOrders.setAdsPromotionRate(Math.div(orderInfo.getAdsPromotionRate() == null ? 0 : orderInfo.getAdsPromotionRate(), 100));
                    dyOrders.setMediaType(orderInfo.getMediaType());
                    dyOrders.setAdsActivityId(orderInfo.getAdsActivityId());
                    dyOrders.setAdsEstimatedTechServiceFee(Math.div(orderInfo.getAdsEstimatedTechServiceFee() == null ? 0 : orderInfo.getAdsEstimatedTechServiceFee(), 100));
                    dyOrders.setAdsFansType(orderInfo.getAdsFansType());
                    dyOrders.setProductActivityId(orderInfo.getProductActivityId());
                    dyOrders.setBizStatus(bizstatus);
                    dyOrders.setUpdateTime(now);
                    dyOrders.setTokenType(0); //抖音抖客订单
                    dyOrders.setTokenId(dyTokens.getAppId());

                    //抖音订单修改
                    dyOrdersMapper.update(dyOrders);

                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error( "--抖音订单下载失败--" + orderInfo.getOrderId()+" err:{}",e);
            }
        }
    }

    @Async("taskExecutor")
    @Override
    public void threadSyncOrder_consumer(List<DyOrderTimeVO> dyOrderTimeVOS, DyTokens token, Integer downType) {
        syncOpenUnitOrder(dyOrderTimeVOS,token,downType);
    }

    private int bizStatus(String orderSubStatusName) {
        switch (orderSubStatusName){
            case "PAY_SUCC":
                return 0;
            case "SETTLE":
                return 1;
            case "CONFIRM":
                return 1;
            case "REFUND":
                return 3;
        }
        return -1;
    }
}
